package com.task.sql.schedule.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.task.sql.schedule.common.ApiResult;
import com.task.sql.schedule.common.PageResult;
import com.task.sql.schedule.constant.ResultCode;
import com.task.sql.schedule.domain.entity.SqlTaskSchedule;
import com.task.sql.schedule.mapper.SqlTaskScheduleMapper;
import com.task.sql.schedule.service.SqlTaskScheduleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.task.sql.schedule.domain.qo.SqlTaskScheduleQO;
import com.task.sql.schedule.domain.vo.SqlTaskScheduleVO;
import com.task.sql.schedule.domain.dto.SqlTaskScheduleDTO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;


/**
 * 1.  服务实现类
 * 2.  3. @author donghai.liu
 * 4. @time 2024-09-10
 */
@Service
public class SqlTaskScheduleServiceImpl extends ServiceImpl<SqlTaskScheduleMapper, SqlTaskSchedule> implements SqlTaskScheduleService {

    @Resource
    private SqlTaskScheduleMapper mapper;

    @Override
    public PageResult<SqlTaskScheduleVO> page(SqlTaskScheduleQO qo) {
        List<SqlTaskScheduleVO> data = mapper.listSqlTaskSchedule(qo);
        int total = mapper.countSqlTaskSchedule(qo);
        PageResult<SqlTaskScheduleVO> pageResult = PageResult.success(data, total);
        pageResult.setPageSize(qo.getPageSize());
        pageResult.setPageNum(qo.getPageNum());
        int pages = total % qo.getPageSize() == 0 ? total / qo.getPageSize() : total / qo.getPageSize() + 1;
        pageResult.setPages(pages);
        return pageResult;
    }

    @Override
    public List<SqlTaskSchedule> listPendingTasks(int failedMaxNum) {
        List<SqlTaskSchedule> sqlTaskSchedules = mapper.listPendingTasks(failedMaxNum);
        return sqlTaskSchedules;
    }

    @Override
    @Transactional
    public ApiResult<Long> save(SqlTaskScheduleDTO dto) {
        SqlTaskSchedule entity = new SqlTaskSchedule();
        BeanUtil.copyProperties(dto, entity);
        mapper.insert(entity);
        return ApiResult.success(entity.getId());
    }

    @Override
    @Transactional
    public ApiResult<Long> update(SqlTaskScheduleDTO dto) {
        if (null == dto.getId()) {
            return ApiResult.error(ResultCode.PARAM_ERROR);
        }
        SqlTaskSchedule entity = new SqlTaskSchedule();
        BeanUtil.copyProperties(dto, entity);
        mapper.updateById(entity);
        return ApiResult.success(entity.getId());
    }
}
